package com.threeti.mecool.core.application.acl;

import com.threeti.mecool.core.application.message.MessageService;
import com.threeti.mecool.core.domain.model.acl.OrgnizationEmployee;
import com.threeti.mecool.core.domain.model.acl.User;
import com.threeti.mecool.core.exception.MessageException;
import com.threeti.mecool.core.infrastructure.persistence.acl.SysRoleRepository;
import com.threeti.mecool.core.infrastructure.persistence.acl.UserRepository;
import com.threeti.mecool.legacy.domain.model.acl.EmployeeLegacy;
import com.threeti.mecool.legacy.infrastructure.persistence.EmployeeLegacyRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {
    public static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserRepository userRepo;

    @Autowired
    private SysRoleRepository sysRoleRepo;
//
//  @Autowired
//  private PermissionAclService aclService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private EmployeeLegacyRepository empLegRepo;

    @Override
    public UserAdapter loadUserByUsername(String loginName) throws UsernameNotFoundException, DataAccessException {
        final User user = userRepo.findByloginName(loginName);

        if (user == null)
            throw new UsernameNotFoundException("用户名不存在: " + loginName);

        //抓取员工在企业中的岗位Title->
        try {
            EmployeeLegacy empLeg = empLegRepo.findOne(user.getEmployee().getEmpId());
            OrgnizationEmployee orgEmp = user.getEmployee();
            if (orgEmp != null) {
                orgEmp.setTitleWithinTheOrg(empLeg.getTitleWithinTheOrg());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //<-

        return new UserAdapter(user);
    }

    @Override
    public User getUserFromSession() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserAdapter) {
            UserAdapter userDetails = (UserAdapter) principal;
            return userDetails.getUser();
        }
        return null;
    }

    @Override
    public User getCurrentUserWithPermissionRoleAndEntries() {
        User user;
        if ((user = getUserFromSession()) == null) return null;
        return userRepo.findWithPermissionRoleAndEntries(user.getLoginName());
    }

    @Override
    @Transactional
    public User register(User newUser) {
        User found = userRepo.findByloginName(newUser.getLoginName());
        if (found != null)
            throw new RuntimeException("帐号已存在: " + found);

        if (newUser.getPermissionRole() == null) throw new RuntimeException("用户的权限角色不能为空");

        newUser.addSystemRole(sysRoleRepo.findByName("ROLE_USER"));//默认即视为系统一般用户
        User user;
        try {
            user = userRepo.saveAndFlush((newUser));
        } catch (DataIntegrityViolationException ex) {
            throw new RuntimeException("无法新增,已存在相同编号的员工: " + newUser.getEmployee().getEmpId(), ex);
        }

        //user = aclService.activatePermissionsBindedWithUser(newUser, true);

        try {
            messageService.confirmAccount(newUser.getLoginName());
        } catch (MessageException e) {
            logger.error("消息服务器异常，无法正常创建账号", e);
            //TODO jay:simply keep silent....
            //throw new RuntimeException("消息服务器异常，无法正常创建账号", e);
        }
        return user;
    }

    @Override
    @Transactional
    public void updateUserBy(Long userId, Long oldRoleIdOfUser, User userWithDataNeedToBeUpdated) {
        User userLoaded = userRepo.findOne(userId);
        userLoaded.setDisplayName(userWithDataNeedToBeUpdated.getDisplayName());
        userLoaded.setEmployee(userWithDataNeedToBeUpdated.getEmployee());
        userLoaded.setLoginName(userWithDataNeedToBeUpdated.getLoginName());
        userLoaded.setImei(userWithDataNeedToBeUpdated.getImei());
        userLoaded.setDisableImeiValidate(userWithDataNeedToBeUpdated.getDisableImeiValidate());

        boolean isRoleChanged = false;

        if (userLoaded.getPermissionRole() == null) throw new RuntimeException("用户的权限角色不能为空");

        if (isRoleChanged = !userLoaded.getPermissionRole().equals(userWithDataNeedToBeUpdated.getPermissionRole())) {
            userLoaded.setPermissionRole(userWithDataNeedToBeUpdated.getPermissionRole());
        }

        try {
            userLoaded = userRepo.saveAndFlush(userLoaded);
        } catch (DataIntegrityViolationException ex) {
            throw new RuntimeException("无法编辑,已存相同编号的员工: " + userLoaded.getEmployee().getEmpId());
        }

        //if (isRoleChanged) {
//			aclService.eraseUserAclSecurityInfoAllWithCache(userLoaded.getLoginName(), oldRoleIdOfUser);
//			aclService.activatePermissionsBindedWithUser(userLoaded, false);
        //aclService.renewAclsRelatedByPermissionRole(userLoaded, oldRoleIdOfUser);
        //}
    }

    @Override
    @Transactional
    public void removeUserFromSystem(User user) {
        userRepo.delete(user);

        //aclService.eraseUserAclSecurityInfoAllWithCache(user.getLoginName());
    }

}
